package com.mdp.arc.archive.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.arc.archive.entity.*;
import com.mdp.arc.archive.mapper.ArchiveMapper;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.BaseService;
import com.mdp.core.utils.BaseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 父类已经支持增删改查操作,因此,即使本类什么也不写,也已经可以满足一般的增删改查操作了.<br> 
 * 组织 com.mdp  顶级模块 arc 大模块 archive 小模块 <br>
 * 实体 Archive 表 arc_archive 当前主键(包括多主键): id; 
 ***/
@Service
public class ArchiveService extends BaseService<ArchiveMapper,Archive> {
	static Logger logger =LoggerFactory.getLogger(ArchiveService.class);
	public static String urlPrefix = "arc/archive/";

	@Autowired
	public ArchiveCategoryService acs;

	/**
	 * 自定义查询，支持多表关联
	 * @param page 分页条件
	 * @param ew 一定要，并且必须加@Param("ew")注解
	 * @param ext 如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
	 * @return
	 */
	public List<Map<String,Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String,Object> ext){
		return baseMapper.selectListMapByWhere(page,ew,ext);
	}

    public Archive getOneArchiveByCategoryId(String categoryId) {
		return super.getOne(QueryTools.initQueryWrapper(Archive.class).eq("category_id",categoryId));
    }


	@Transactional
	public void closeComment(List<String> ids) {
		baseMapper.closeComment(ids);
	}

	@Transactional
	public void openComment(List<String> ids) {
		baseMapper.openComment(ids);
	}

	/**
	 * 更新tagIds,tagNames两个字段为最新的值
	 *
	 * @param archiveId
	 * @param tagIds
	 * @param tagNames
	 */
	public void updateTagsByArchiveId(String branchId, String archiveId, String tagIds, String tagNames) {

		Map<String, Object> p = new HashMap<>();
		p.put("archiveId", archiveId);
		p.put("tagIds", tagIds);
		p.put("tagNames", tagNames);
		p.put("branchId", branchId);
		baseMapper.updateTagsByArchiveId(p);

	}

	@Transactional
	public void publishArchive(ArchiveCategoryVo acVo) {
		ArchiveCategory a = new ArchiveCategory();
		a.setArchiveId(acVo.getArchiveId());
		acs.deleteByWhere(a);
		if (acVo.getCategoryIds() != null && acVo.getCategoryIds().length > 0) {
			List<ArchiveCategory> acList = new ArrayList<>();
			for (String categoryId : acVo.getCategoryIds()) {
				ArchiveCategory ac = new ArchiveCategory();
				ac.setArchiveId(acVo.getArchiveId());
				ac.setCategoryId(categoryId);
				acList.add(ac);
			}
			acs.batchInsert(acList);
			Archive archiveUpdate=new Archive();
			archiveUpdate.setId(acVo.getArchiveId());
			archiveUpdate.setStatus("1");
			archiveUpdate.setCanComment("1");
			this.updateSomeFieldByPk(archiveUpdate);
		}
	}

	@Transactional
	public void unPublishArchive(List<String> ids) {
		this.editSomeFields(map("ids",ids,"status","2"));
	}


	public int updateByPk(Archive archive) {
		return super.updateByPk(archive);
	}

	String getHtmlContext(String title, String richText) {
		StringBuffer sb = new StringBuffer();
		sb.append("<!DOCTYPE html>\n");
		sb.append("<html>\n");
		sb.append(" <head>\n");
		sb.append("   <meta charset='utf-8'>\n");
		sb.append("   <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>\n");
		sb.append("   <meta name='renderer' content='webkit'>\n");
		sb.append("   <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'>\n");
		sb.append("   <title>" + title + "</title>\n");
		sb.append(" </head>\n");
		sb.append(" <body>\n");
		sb.append(richText);
		sb.append("\n");
		sb.append(" </body>\n   ");
		sb.append("</html>\n");
		return sb.toString();
	}

	public int deleteByPk(Archive archive) {

		return super.deleteByPk(archive);
	}



	public void publishForProcessApprova(Map<String, Object> flowVars) {
		String agree = (String) flowVars.get("agree");
		String bizKey = (String) flowVars.get("bizKey");
		String eventName = (String) flowVars.get("eventName");
		String archiveId = (String) flowVars.get("archiveId");
		Map<String, Object> map = new HashMap();
		map.put("archiveId", archiveId);
		ArchiveCategoryVo ac = new ArchiveCategoryVo();
		ac.setArchiveId(archiveId);
		List<String> categoryIds = (List<String>) flowVars.get("categoryIds");
		String[] strids = (String[]) categoryIds.toArray(new String[0]);
		ac.setCategoryIds(strids);
		if (!"archive_register".equals(bizKey)) {
			throw new BizException("不支持的业务,请上送业务编码【bizKey】参数,文章发布审批业务编码为【archive_register】");
		}
		if ("complete".equals(eventName)) {
			if ("1".equals(agree)) {
				publishArchive(ac);
				map.put("status", "1");
				baseMapper.updateArchiveStaticById( map);
			} else {
				map.put("status", "0");
				baseMapper.updateArchiveStaticById(map);
			}
		} else {
			if ("PROCESS_STARTED".equals(eventName)) {
				map.put("status", "3");
				baseMapper.updateArchiveStaticById(map);
			} else if ("PROCESS_COMPLETED".equals(eventName)) {
				if ("1".equals(agree)) {
					publishArchive(ac);
					map.put("status", "1");
					baseMapper.updateArchiveStaticById(map);
				} else {
					map.put("status", "0");
					baseMapper.updateArchiveStaticById(map);
				}
			} else if ("PROCESS_CANCELLED".equals(eventName)) {
				map.put("status", "0");
				baseMapper.updateArchiveStaticById(map);
			}
		}
	}

	@Transactional
	public int addArchive(ArchiveAddVo archiveVo) {
		Archive archive=archiveVo.getArchive();
		int i=this.insert(archiveVo.getArchive());
		if(StringUtils.hasText(archiveVo.getCategoryId())){
			ArchiveCategory ac = new ArchiveCategory();
			ac.setArchiveId(archive.getId());
			ac.setCategoryId(archiveVo.getCategoryId());
			this.acs.insert(ac);

		}
		return i;
	}

	public List<Map<String, Object>> myCollect(Map<String, Object> archive) {
		return baseMapper.myCollect(archive);
	}

	public UserForumCpdVo userForumCpd(String userid) {
		return baseMapper.userForumCpd(userid);
	}


	public void updateUpNums(List<String> archiveIds) {
		baseMapper.updateUpNums(archiveIds);
	}

	public void updateCommentNums(List<String> archiveIds) {
		baseMapper.updateCommentNums(archiveIds);
	}

	public void updateCollectNums(List<String> archiveIds) {
		baseMapper.updateCollectNums(archiveIds);
	}
	public void upReadNums(String id,Integer readNums) {
		baseMapper.upReadNums(BaseUtils.map("id",id,"readNums",readNums));
	}

	public List<Map<String, Object>> selectFrinedMessage(IPage page, Map<String, Object> params) {
		return baseMapper.selectFrinedMessage(page,params);
	}
}

